package com.msmall.community.common.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.msmall.base.util.Constants;
import com.msmall.base.util.StringUtil;
import com.msmall.base.util.UAUtil;
import com.msmall.community.ApplicationManager;
import com.msmall.community.common.OnlineUser;
import com.msmall.community.user.service.UserManager;

public class UserAgentListener implements ServletRequestListener{

	public void requestDestroyed(ServletRequestEvent sre) {

	}

	public void requestInitialized(ServletRequestEvent sre) {
		HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
		HttpSession session = request.getSession();  //如果是第一创建Session，此时执行sessionCreated方法
		Long userid = (Long) session.getAttribute(Constants.SESSION_USER_ID_KEY);
		OnlineUser oUser = OnlineUser.getOnlineUsers().get(userid);
		if(oUser == null){
			OnlineUser.anonymousLogout(userid);
			String username = "";
			do {
				userid = StringUtil.randomLong(7);
	        } while (OnlineUser.getOnlineUsers().get(userid) != null);
			username = Constants.USER_ANONYMOUS + StringUtil.randomString(5);
			UserManager userManager = (UserManager) ApplicationManager.appContext.getBean("userManager");
			userManager.createAnonymousAccount(userid, username);
			OnlineUser.anonymousCreated(userid, session);
		}
		if(oUser != null && oUser.getUserAgentBean() == null){
			UserAgentBean bean = new UserAgentBean();
			bean.setUserAgentType(UAUtil.getUserAgentType(request));
			bean.setTelno(request.getHeader("x-up-calling-line-id"));
			bean.setUserAgent(request.getHeader("User-Agent"));
			oUser.setUserAgentBean(bean);
		}
	}

}
